package com.xx.springboot.DataStructure.LeetCode.LinkedList;

/**
 * 给定一个链表: 1->2->3->4->5, 和 n = 2.
 * 当删除了倒数第二个节点后，链表变为 1->2->3->5.
 * Created by xiaoxiunique on 2018-8-10.
 */
public class removeNthFromEnd {

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummyHead = new ListNode(-1);
        dummyHead.next = head;
        ListNode l = dummyHead;
        ListNode r = dummyHead;
        for (int i = 0; i < n; i++)
            r = r.next;

        while (r.next != null) {
            r = r.next;
            l = l.next;
        }

        ListNode delNode = l.next;
        l.next = delNode.next;
        delNode.next = null;
        return dummyHead.next;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6};
        ListNode node = new ListNode(arr);
        System.out.println(node);
        System.out.println( (new removeNthFromEnd()).removeNthFromEnd(node, 4) );
    }

}
